package com.rms.recruit_management_system.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.MD5;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rms.recruit_management_system.mapper.InterviewMapper;
import com.rms.recruit_management_system.mapper.ResumeMapper;
import com.rms.recruit_management_system.mapper.UserMapper;
import com.rms.recruit_management_system.pojo.Administrator;
import com.rms.recruit_management_system.pojo.Interview;
import com.rms.recruit_management_system.pojo.Resume;
import com.rms.recruit_management_system.pojo.User;
import com.rms.recruit_management_system.service.UserService;
import com.rms.recruit_management_system.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ResumeMapper resumeMapper;
    @Autowired
    private InterviewMapper interviewMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private JavaMailSender javaMailSender;
    @Value("${spring.mail.username}")
    private String username;
    @Override
    public User userLogin(User user) {

        return userMapper.selectOne(new QueryWrapper<User>()
                .eq("username", user.getUsername())
                .eq("password", MD5.create().digestHex(user.getPassword())));
    }

    @Override
    public void userRegister(User user) {
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        user.setPassword(MD5.create().digestHex(user.getPassword()));
        userMapper.insert(user);
    }

    @Override
    public User getUserById(Integer userId) {
        return userMapper.selectById(userId);
    }

    @Override
    public void updateUser(User user) {
        user.setUpdateTime(LocalDateTime.now());
        userMapper.updateById(user);
    }

    @Override
    public void deleteUser(Integer userId) {
        userMapper.deleteById(userId);
    }

    @Override
    public IPage<User> getUserPage(Integer pageNum, Integer pageSize, String search) {
        Page<User> page=new Page<>(pageNum,pageSize);
        LambdaQueryWrapper<User> wrapper= Wrappers.<User>lambdaQuery();
        if(StrUtil.isNotBlank(search)){
            wrapper.like(User::getUsername,search).or().like(User::getEmail,search).or().like(User::getPhone,search);
        }
        return userMapper.selectPage(page,wrapper);
    }

    @Override
    public List<Resume> getResumeByUserId(Integer userId) {
        return resumeMapper.selectList(new QueryWrapper<Resume>().eq("user_id", userId));
    }

    @Override
    public List<Interview> getInterviewByUserId(Integer userId) {
        return interviewMapper.selectList(new QueryWrapper<Interview>().eq("user_id", userId));
    }

    @Override
    public void findPassword(String email) {
        User user=userMapper.selectOne(new QueryWrapper<User>().eq("email",email));
        int min=100000;
        int max=999999;
        int code= ThreadLocalRandom.current().nextInt(min,max+1);
        String coderStr=String.valueOf(code);
        String key="code_"+email;
        redisTemplate.opsForValue().set(key,coderStr,3, TimeUnit.MINUTES);
        SimpleMailMessage message = new SimpleMailMessage();
        if (user != null && user.getEmail() != null) {
            message.setFrom(username);
            message.setTo(email);
            log.info("email: {}", email);
            message.setSubject("验证码");
            message.setText("您的验证码为：" + code);
            javaMailSender.send(message);
        }else {
            log.warn("邮箱不存在",email);
        }
    }

    @Override
    public User getUserByEmail(String Email) {
        return userMapper.selectOne(new QueryWrapper<User>().eq("email",Email));
    }
}
